package com.example.flowerpcback.controller;

import com.example.flowerpcback.resp.CommonResp;
import com.example.flowerpcback.resp.FileResp;
import com.example.flowerpcback.services.TestService;
import com.example.flowerpcback.utils.Uploadaliyun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;


@RestController //这是返回接口
@RequestMapping("/file")
public class FileController {

    private static final Logger LOG = LoggerFactory.getLogger(FileController.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TestService testService;

    @PostMapping("/upload")
    public CommonResp<FileResp> upload(@RequestBody MultipartFile files)throws Exception{
        FileResp fileResp = Uploadaliyun.upFile(files,"document");
        CommonResp<FileResp> commonResp = new CommonResp<>();
        commonResp.setData(fileResp);
        return  commonResp;
    }

    @GetMapping("/delete")
    public CommonResp<String> delete(@Valid String fileName)throws Exception{
        CommonResp<String> commonResp = new CommonResp<>();
        String res = Uploadaliyun.deleteFile(fileName);
        if(res == "1"){
            commonResp.setData("删除成功!");
            return  commonResp;
        } else {
            commonResp.setData("删除失败!");
            commonResp.setCode(500);
            commonResp.setMessage("删除失败!");
            return  commonResp;
        }

    }

    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> download(@Valid String fileName) throws IOException {

        // 调用文件下载方法
        InputStream inputStream = Uploadaliyun.downloadFile(fileName);
        // 设置文件响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + fileName);
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }

}

